package fr.web325.dao;

import fr.web325.bean.Notice;
import fr.web325.utils.QueryRunnerUtils;
import fr.web325.bean.Book;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

// 书本dao类
public class BookDao {
    public Class<Book> bookClass = Book.class;

    // 查询所有订单列表
    public List<Book> getBookList() throws SQLException {
        // 获取数据库连接池对象
        QueryRunner qr = new QueryRunner(QueryRunnerUtils.getDateSource());
        // 查询并返回user对象
        return qr.query("select * from products", new BeanListHandler<>(bookClass));
    }

    // 根据ID查询书本
    public Book getBookById(String id) throws SQLException {
        // 获取数据库连接池对象
        QueryRunner qr = new QueryRunner(QueryRunnerUtils.getDateSource());
        // 查询并返回book对象
        return qr.query("select * from products where id=?", new BeanHandler<>(bookClass), id);
    }

    // 根据book类插入书本
    public Boolean addBook(Book book) throws SQLException {
        // 获取数据库连接池对象
        QueryRunner qr = new QueryRunner(QueryRunnerUtils.getDateSource());
        return qr.update("insert into products(id,name,price,category,pnum,imgurl,description) values (?,?,?,?,?,?,?)",book.getId(),book.getName(),book.getPrice(),book.getCategory(),book.getPnum(),book.getImgurl(),book.getDescription()) > 0;
    }

    // 根据id删除book
    public Boolean removeBookById(String id) throws SQLException {
        // 获取数据库连接池对象
        QueryRunner qr = new QueryRunner(QueryRunnerUtils.getDateSource());
        return qr.update("delete from products where id=?", id) > 0;
    }

    // 根据ID修改公告
    public Boolean editBook(Book book) throws SQLException {
        // 获取数据库连接池对象
        QueryRunner qr = new QueryRunner(QueryRunnerUtils.getDateSource());
        return qr.update("update products set name=?,price=?,category=?,pnum=?,description=?,imgurl=? where id=?",book.getName(),book.getPrice(),book.getCategory(),book.getPnum(),book.getDescription(),book.getImgurl(),book.getId()) > 0;
    }
}
